package com.sakura.mybatis.version2.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author Sakura
 * @Date 2022/11/2 13:01
 * @Version 1.0
 */
public class SqlSessionUtils {
    public static SqlSession getSqlSession() {
        SqlSession sqlSession = null;
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }

    public static SqlSession getSqlSession(String name) {
        SqlSession sqlSession = null;
        if (StrUtil.isNotBlank(name)) {
            try {
                InputStream is = Resources.getResourceAsStream(name);
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                sqlSession = sqlSessionFactory.openSession(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sqlSession;
    }
}
